<template>
    <div>
       <table border="1" width="700" style="border-collapse: collapse">
          <caption>
             购物车
          </caption>
          <thead>
             <tr>
                <th>
                   <input type="checkbox" v-model="change" /> <span>全选</span>
                </th>
                <th>名称</th>
                <th>价格</th>
                <th>数量</th>
                <th>总价</th>
                <th>操作</th>
             </tr>
          </thead>
          <tbody>
             <tr v-for="(obj,index) in goodList" :key="index">
                <td>
                   <input type="checkbox" v-model="obj.checked" />
                </td>
                <td>{{obj.name}}</td>
                <td>{{obj.price}}</td>
                <td>
                   <button @click="minus(index)">-1</button>
                   {{obj.num}}
                   <button @click="add(index)">+1</button>
                </td>
                <td>{{obj.price*obj.num}}</td>
                <td>
                   <button @click="del(index)">删除</button>
                </td>
             </tr>
          </tbody>
          <tfoot>
             <tr>
                <td>合计:</td>
                <td colspan="5">
                   {{sum}}
                </td>
             </tr>
          </tfoot>
       </table>
    </div>
 </template>
  
 <script>
 export default {
    computed: {
       goodList() {
          return this.$store.state.goodList
       },
       change: {
          set(val) {
             this.$store.state.goodList.forEach(item => item.checked = val)
          },
          get() {
             return this.$store.state.goodList.every(item => item.checked)
          }
       },
       sum() {
          return this.$store.state.goodList.reduce((prev, item) => {
             if (item.checked) {
                return prev + item.num * item.price
             } else {
                return prev
             }
          }, 0)
       }
    },
    methods: {
       minus(index) {
          this.$store.commit('MINUS', index)
       },
       add(index) {
          this.$store.commit('ADD', index)
       },
       del(index) {
          this.$store.commit('DEL', index)
       }
    }
 };
 </script>
  
 <style>
 
 </style>